from rest_framework import serializers
from .models import ForumPost, PostImage, PostLike, PostComment
from users.serializers import UserSerializer

class PostImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostImage
        fields = ['url']

class ForumPostSerializer(serializers.ModelSerializer):
    user = UserSerializer()  # 嵌套作者信息
    images = PostImageSerializer(many=True)
    like_count = serializers.IntegerField(source='postlike_set.count', read_only=True)
    comment_count = serializers.IntegerField(source='postcomment_set.count', read_only=True)
    is_liked = serializers.SerializerMethodField()
    is_favorited = serializers.SerializerMethodField()

    class Meta:
        model = ForumPost
        fields = [
            'id', 'user', 'content', 'images', 'title',
            'like_count', 'comment_count', 'created_at',
            'is_liked','is_favorited'
        ]

    def get_is_liked(self, obj):
        request = self.context.get('request')
        if request and hasattr(request, 'user') and request.user.is_authenticated:
            return obj.postlike_set.filter(user=request.user).exists()
        return False

    def get_is_favorited(self, obj):
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.postfavorite_set.filter(user=request.user).exists()
        return False

class PostCommentSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)

    class Meta:
        model = PostComment
        fields = ['id', 'user', 'content', 'created_at']


class ForumPostCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = ForumPost
        fields = ['title', 'content']


